from django.db.models import Q
from rest_framework.decorators import api_view
from rest_framework.request import Request
from rest_framework.response import Response

from api.serializers.product_serializer import ProductListResponseSerializer
from app.models import ProductSpec, Product


@api_view(['GET'])
def search(request: Request, keyword: str):
    queryset = ProductSpec.objects.filter(Q(name__contains=keyword) |
                                          Q(product__name__contains=keyword) |
                                          Q(product__description__contains=keyword))
    products = set([spec.product for spec in queryset])
    serializer = ProductListResponseSerializer(products, many=True)
    return Response(serializer.data)


@api_view(['GET'])
def search_product_name(request: Request, keyword: str):
    queryset = Product.objects.filter(name__startswith=keyword)
    data = [product.name for product in queryset]
    return Response(data)
